<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'

const router = useRouter()

// 地址列表
const addresses = ref([])

// 新地址表单
const newAddress = ref({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
})

// 编辑地址时的索引
const editingIndex = ref(-1)

// 表单验证
const validateForm = () => {
  if (!newAddress.value.name) {
    showToast('请输入收货人姓名')
    return false
  }
  if (!newAddress.value.phone) {
    showToast('请输入手机号')
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(newAddress.value.phone)) {
    showToast('手机号格式不正确')
    return false
  }
  if (!newAddress.value.province || !newAddress.value.city || !newAddress.value.district) {
    showToast('请选择省市区')
    return false
  }
  if (!newAddress.value.detail) {
    showToast('请输入详细地址')
    return false
  }
  return true
}

// 保存地址
const saveAddress = () => {
  if (!validateForm()) return

  if (editingIndex.value === -1) {
    // 添加新地址
    addresses.value.push({ ...newAddress.value })
    showToast('地址添加成功')
  } else {
    // 更新地址
    addresses.value[editingIndex.value] = { ...newAddress.value }
    showToast('地址更新成功')
  }

  // 重置表单
  resetForm()

  // 保存到 localStorage
  localStorage.setItem('addresses', JSON.stringify(addresses.value))
}

// 编辑地址
const editAddress = (index) => {
  editingIndex.value = index
  newAddress.value = { ...addresses.value[index] }
}

// 删除地址
const deleteAddress = (index) => {
  showConfirmDialog({
    title: '删除地址',
    message: '确定要删除这个地址吗？',
  }).then(() => {
    addresses.value.splice(index, 1)
    localStorage.setItem('addresses', JSON.stringify(addresses.value))
    showToast('地址删除成功')
  }).catch(() => {
    // 取消操作
  })
}

// 设为默认地址
const setDefault = (index) => {
  // 先将所有地址设为非默认
  addresses.value.forEach(addr => {
    addr.isDefault = false
  })
  // 设置选中地址为默认
  addresses.value[index].isDefault = true
  localStorage.setItem('addresses', JSON.stringify(addresses.value))
  showToast('默认地址设置成功')
}

// 重置表单
const resetForm = () => {
  newAddress.value = {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  }
  editingIndex.value = -1
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件挂载时从 localStorage 获取地址数据
onMounted(() => {
  const savedAddresses = localStorage.getItem('addresses')
  if (savedAddresses) {
    addresses.value = JSON.parse(savedAddresses)
  }
})
</script>

<template>
  <div class="settings-container">
    <van-nav-bar
      title="地址管理"
      left-arrow
      @click-left="goBack"
    />

    <div class="address-list" v-if="addresses.length > 0">
      <div
        v-for="(address, index) in addresses"
        :key="index"
        class="address-item"
      >
        <div class="address-info" @click="editAddress(index)">
          <div class="address-header">
            <span class="name">{{ address.name }}</span>
            <span class="phone">{{ address.phone }}</span>
            <van-tag v-if="address.isDefault" type="danger" size="mini">默认</van-tag>
          </div>
          <div class="address-detail">
            {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
          </div>
        </div>
        <div class="address-actions">
          <van-button
            size="small"
            type="primary"
            @click.stop="setDefault(index)"
            v-if="!address.isDefault"
          >
            设为默认
          </van-button>
          <van-button
            size="small"
            @click.stop="editAddress(index)"
          >
            编辑
          </van-button>
          <van-button
            size="small"
            type="danger"
            @click.stop="deleteAddress(index)"
          >
            删除
          </van-button>
        </div>
      </div>
    </div>

    <van-empty
      description="暂无收货地址"
      v-else
    />

    <div class="form-container">
      <h3>{{ editingIndex === -1 ? '新增地址' : '编辑地址' }}</h3>
      <van-cell-group inset>
        <van-field
          v-model="newAddress.name"
          label="收货人"
          placeholder="请输入收货人姓名"
          required
        />
        <van-field
          v-model="newAddress.phone"
          label="手机号"
          placeholder="请输入手机号"
          required
        />
        <van-field
          v-model="newAddress.province"
          label="省份"
          placeholder="请输入省份"
          required
        />
        <van-field
          v-model="newAddress.city"
          label="城市"
          placeholder="请输入城市"
          required
        />
        <van-field
          v-model="newAddress.district"
          label="区/县"
          placeholder="请输入区/县"
          required
        />
        <van-field
          v-model="newAddress.detail"
          label="详细地址"
          placeholder="请输入详细地址"
          required
          type="textarea"
          rows="2"
        />
        <van-checkbox
          v-model="newAddress.isDefault"
          shape="square"
          style="margin: 16px;"
        >
          设为默认地址
        </van-checkbox>
      </van-cell-group>

      <div class="form-actions">
        <van-button
          type="primary"
          block
          @click="saveAddress"
        >
          {{ editingIndex === -1 ? '添加地址' : '更新地址' }}
        </van-button>
        <van-button
          v-if="editingIndex !== -1"
          block
          @click="resetForm"
          style="margin-top: 10px;"
        >
          取消编辑
        </van-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.settings-container {
  padding-bottom: 20px;

  .address-list {
    padding: 16px;

    .address-item {
      background: var(--van-background-2);
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 12px;

      .address-info {
        cursor: pointer;

        .address-header {
          display: flex;
          align-items: center;
          margin-bottom: 8px;

          .name {
            font-size: 16px;
            font-weight: bold;
            margin-right: 12px;
          }

          .phone {
            font-size: 14px;
            color: var(--van-text-color-2);
            flex: 1;
          }
        }

        .address-detail {
          font-size: 14px;
          color: var(--van-text-color);
          line-height: 1.5;
        }
      }

      .address-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 10px;
      }
    }
  }

  .form-container {
    margin-top: 20px;
    padding: 0 16px;

    h3 {
      margin-bottom: 16px;
      font-size: 18px;
      color: var(--van-text-color);
    }

    .form-actions {
      margin-top: 20px;
    }
  }
}

[data-theme="dark"] {
  .address-item {
    background: var(--van-background-2);
  }
}
</style>